#ifndef DAVPUT_H
#define DAVPUT_H


#include "base_modul.h"
#include "qxml.h"
#include "basedav.h"
#include "networkdav.h"

class NetworkDav;
    
class DavPUT : public QObject, public Base_Modul
{
    Q_OBJECT
//
public: 
    DavPUT( NetworkDav *db , QFile * locfile , const QString remotefile , const QString path , QWidget * parent )  /* open on read mode close on end ****/
{
    loopnummer = -1;
    wakeaborter = false;
    endarrivo = false;
    printsecond = 0;
   ///// db = db;
    gostart.start();
    pathregister = path;
    actualurl = remotefile;
    davinfo = new QHttp();
    davinfo->setHost(db->Host(),db->Port());
    davinfo->setUser(db->User(),db->Pass());
    QApplication::restoreOverrideCursor();
    
    QFileInfo info(locfile->fileName());
    filezsize = info.size();
    
    
    dlg = new QProgressDialog(parent,Qt::Window);
    dlg->setCancelButtonText(tr("Abort action Upload"));
    dlg->setWindowTitle (tr("Upload....."));
    dlg->setLabelText (tr("Upload to WebDav Server File \"%1\" ").arg( actualurl ));
    dlg->setMinimumDuration(1500);
    dlg->show();
    
    qt_unlink(GETSTSTREAM); 
    BeamUpFile = locfile;
    BeamLogFile = new QFile(GETSTSTREAM);     /* responder file info */
    BeamLogFile->open(QIODevice::ReadWrite);
    
    
    QHttpRequestHeader header("PUT", actualurl ,1,1);   /* header */
    header.setValue("Host", db->Host());
    ///////header.setValue("Depth","1");
    header.setValue("User-Agent", WEBAGENTNAME );
    header.setValue("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    header.setValue("Accept-Language", "it,de-de;q=0.8,it-it;q=0.6,en-us;q=0.4,en;q=0.2");
    header.setValue("Connection", "keep-alive");
    david = davinfo->request(header,BeamUpFile,BeamLogFile);
    connect(dlg, SIGNAL(canceled()), this , SLOT(CloseActual()));
      connect(davinfo, SIGNAL(dataSendProgress(int, int)), this, SLOT(SendStatus(int, int)));
      /////////////////connect(davinfo, SIGNAL(done(bool)), this, SLOT(DavWake(bool)));
      connect(davinfo, SIGNAL(requestFinished(int, bool)), this, SLOT(Wake_Finish(int, bool)));
      connect(davinfo, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)), this, SLOT(RegisterBackHeader(const QHttpResponseHeader &)));
     
        
    
}
void  SetPosition( int position )
{
  loopnummer =   position;  
}
protected:
 void DavClose()
{
  BeamLogFile->close();
  BeamUpFile->close();
  davinfo->close();
}
private:
  QString pathinfofile;
  QProgressDialog *dlg;
  QTime gostart;
  QHttp *davinfo;
  int david;
  int printsecond;
  qint64 filezsize;
  int interval;
  bool  wakeaborter;
  bool endarrivo;
  int loopnummer;
  int statuscode;
  QFile *BeamUpFile;
  QFile *BeamLogFile;
  QString actualurl;
  QString humanwait;
  QString speeder;
  QString pathregister;
  QString xmlinfo;
  QString dummypath;
  QString DisplayName;
signals:
  void WarningMsg( QString e );
  ///////void MDavInfoXmlItem( QString info , QString pat );
  void UploadFileLoop( int next); 
  //////void Statusloop( int re , int to );
public slots:
 void DavWake( bool error )
{
      /////////////////////qDebug() << "#### DavWake  Last error found...  ->" << error; 
     if (wakeaborter) {
     return;
   }
}


void CloseActual()
{
     wakeaborter = true;
    
     if (endarrivo) {
      return;
     }
    
       ///////////////////qDebug() << "#### CloseActual...  ->" << wakeaborter; 
       davinfo->abort();
       DavClose();
    
        
    
       emit WarningMsg(tr("Abort on url: %1\nErrorMsg %2").arg(actualurl).arg(davinfo->errorString()));
} 



void  Wake_Finish( int requestId, bool error )
{
    //////////////////qDebug() << "#### Wake_Finish...  ->" << wakeaborter; 
    
   if (requestId != david ) {
     return;
   }
    if (wakeaborter) {
     return;
   }
    endarrivo = true;
   
    QHttpResponseHeader lastheader = davinfo->lastResponse();
    statuscode = lastheader.statusCode();
    DavClose();
    if (error) {
    emit WarningMsg(tr("Error on url: %1\nErrorMsg %2").arg(actualurl).arg(davinfo->errorString()));
    return;
    } 
    ////////////////////qDebug() << "#### HEADER STATUS CODE  ->" << statuscode; 
    if (statuscode == 201 || statuscode == 204 ) {
    RegisterStream();
    } else {
    emit WarningMsg(tr("Error on url: %1\nErrorMsg %2\nHeader Status code %3").arg(actualurl).arg(davinfo->errorString()).arg(statuscode)); 
    }
}

void RegisterStream()
{
   /////////////qDebug() << "#### RegisterStream...  ->" << wakeaborter  << loopnummer; 
   
   
   if (loopnummer == 0 or loopnummer > 0) {
       int next = loopnummer + 1;
       emit UploadFileLoop(next);
     loopnummer = -1;       
     return;
   } else {
     emit WarningMsg(tr("Error on url: %1 No Nr. Found!").arg(actualurl));
     return;       
   }
    
}


void RegisterBackHeader(const QHttpResponseHeader &responseHeader )
{
   statuscode = responseHeader.statusCode();  
      
}

void  SendStatus( int bytesRead, int totalBytes )
{
    QString elapettime,ssec,smin,shor;
    
    if (wakeaborter) {
     return;
   }
if (bytesRead == totalBytes) {
       endarrivo = true;
   }
   int mmse = gostart.elapsed();
   int sec_el  = mmse / 1000;
   int kilobitereader,waitpleasesec,kilosec1,kilosec2;
   uint remainbyte, waitms, waitsecond;
   uint mancabytes = totalBytes - bytesRead;
   
   if (printsecond == 0) {
   speeder = QString("Wait please calculate Speed...");    
   humanwait = TimeaGo(gostart.elapsed(),0);   /* waittime please */
   }
   
   if (printsecond != sec_el) {   /* start from 0   must wait to have minimum on second ! */
       ////////////qDebug() << "#### printsecond  ->" << printsecond;
       /* each second work ! readable! */
       qint64 filereadnow = BeamUpFile->pos();   /* pointer to qfile upload  filezsize = qfileinfo.size() */
       kilosec2 = (filereadnow / 1024) / sec_el;  /* kilo on sec */
       speeder = QString("on %1 Kb/sec.").arg(kilosec2);
       speeder.append(" Upload ");
       speeder.append(BiteorMega(filezsize - filereadnow));
       humanwait = TimeaGo(0,(((filezsize - filereadnow) / 1024) / kilosec2));   /* waittime please */
       printsecond = sec_el;
   }
   elapettime = QString("Time:%1 %2").arg(humanwait).arg(speeder);
   dlg->setLabelText (tr("Upload to WebDav Server File \"%1\" - %2").arg( actualurl ).arg(elapettime));
   dlg->setMaximum(totalBytes);
   dlg->setValue(bytesRead);
    
}

};

	
	
	
	
	
	
	
	


//
#endif // DAVPUT_H

